import {
  Message
} from 'element-ui'
import {
  Loading
} from 'element-ui'

/**
 * 对Date的扩展，将 Date 转化为指定格式的String
 *  月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
 *  年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 *  例子：
 *  (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 *  (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
 *  (new Date()).Format("yyyy-MM-dd hh:mm:ss")   ==> 2006-07-02 08:09:04
 *  (new Date()).Format()   ==> 2006-07-02 08:09:04
 * @param fmt 转成string的格式，若不传参数采用默认（yyyy-MM-dd hh:mm:ss）
 * @returns {*} int转成的string
 * @constructor
 */
Date.prototype.format = function(fmt = "yyyy/MM/dd hh:mm") {
  //若时间为0，则返回''
  if (!this.getTime()) return '';
  //转字符串
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (!time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * 日期字符串转日期(2020-02-13T12:12:31.000+0000  ==>  2020-02-13)
 * @param dateStr
 * @returns {*}
 */
export function str2Date(dateStr) {
  if (!dateStr || dateStr.indexOf("T") == -1) return dateStr;
  var arr = dateStr.split("T");
  var date = new Date(arr[0]);
  date = new Date(date.getTime());
  var month = prefixZero(date.getMonth() + 1);
  var currentDate = prefixZero(date.getDate());
  return date.getFullYear() + "-" + month + "-" + currentDate;
}

function prefixZero(num) {
  return num < 10 ? '0' + String(num) : num;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

export function deepClone(origin, target) {
  var target = target || {},
    toStr = Object.prototype.toString,
    arrStr = "[object Array]";
  for (var prop in origin) {
    if (origin.hasOwnProperty(prop)) {
      if (origin[prop] !== "null" && typeof(origin[prop]) == "object") {
        target[prop] = (toStr.call(origin[prop]) == arrStr) ? [] : {};
        deepClone(origin[prop], target[prop]);
      } else {
        target[prop] = origin[prop]
      }
    }
  }
}

/**
 * 数组排序
 *
 * @param {Array} dataSource 需要排序的数据源
 * @param {String} key 排序的字段
 * @param {String} type 排序方式：默认asc,其它为desc
 */
export function sort(dataSource, key, type = 'ASC') {
  var sortModel = [],
    sx = "x." + key,
    sa = "a." + key,
    sb = "b." + key;
  var isNum = true;
  dataSource.forEach(x => {
    var s = eval(sx);
    sortModel.push(s);
    if (isNaN(Number(s))) {
      isNum = false;
    }
  });
  if (isNum) {
    sortModel.sort((a, b) => {
      return a - b;
    });
  } else {
    sortModel.sort();
  }
  dataSource.sort((a, b) => {
    if (type.toUpperCase() == 'ASC') {
      return sortModel.indexOf(eval(sa)) - sortModel.indexOf(eval(sb));
    } else {
      return sortModel.indexOf(eval(sb)) - sortModel.indexOf(eval(sa));
    }
  });
}

/**
 * @param {Object} param获取链接里面的参数
 */
export function getUrlParam(param) {
  var url = window.location.href;
  param = param.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + param + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

export function showSuccessMessage(msg, onClose, timelong = 1500) {
  Message({
    showClose: true,
    message: msg === null || msg === '' ? '操作成功' : msg,
    type: 'success',
    center: true,
    duration: timelong,
    onClose: onClose
  })
}

export function showErrorMessage(msg, onClose, timelong = 3000) {
  Message({
    showClose: true,
    message: msg === null || msg === '' ? '系统忙请稍后再试' : msg,
    type: 'error',
    center: true,
    duration: timelong,
    onClose: onClose
  })
}

/**
 * loading 实例
 */
const LoadingInstance = (function() {
  let instance = undefined
  let options = {
    body: false,
    fullscreen: false,
    lock: true,
    text: '加载中...',
    spinner: 'el-icon-loading',
  }
  let _static = {
    open(op) {
      if (!instance) {
        let o = Object.assign({}, options, op);
        //console.log(o)
        instance = Loading.service(o);
      }
      return instance
    },
    close() {
      instance.close();
      instance = undefined;
    }
  }
  return _static
})()

/**
 * 是否显示加载
 *
 * @param isLoading
 * @param options
 */
export function loading(isLoading = true, options) {
  if (isLoading) {
    LoadingInstance.open(options);
  } else {
    LoadingInstance.close();
  }
}

// 金额 千分位 加逗号 并且 末尾 保留两位小数
export function numFormat (value) {
    if(!value) return '0.00'
    value = value.toString().split('.').length>1?value.toString():parseFloat(value).toFixed(2).toString();
    // 小数点后面有大于2位的小数
    value = value.split(".")[1].length>2?parseFloat(value).toFixed(2):value;
    // var intPart = Math.trunc(value)// 获取整数部分
    var intPart = value.split(".")[0];
    var intPartFormat = '';
    if(intPart=='-0'){
      intPartFormat = '-0'
    }else{
      intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') // 将整数部分逢三一断
    }
    var floatPart = '.00' // 预定义小数部分
    var value2Array = value.split('.')
    // =2表示数据有小数位
    if(value2Array.length === 2) {
        floatPart = value2Array[1].toString() // 拿到小数部分
        if(floatPart.length === 1) { // 补0,实际上用不着
            return intPartFormat + '.' + floatPart + '0'
        } else {
            return intPartFormat + '.' + floatPart
        }
    } else {
        return intPartFormat + floatPart
    }
}



export default {
  deepClone,
  param2Obj,
  formatTime,
  parseTime,
  str2Date,
  showSuccessMessage,
  showErrorMessage,
  getUrlParam,
  loading,
  numFormat
}
